import { ref, computed, watch } from 'vue';

const useCountdown = (duration) => {
    const remainingTime = ref(duration);
    const isActive = computed(() => remainingTime.value > 0);

    const startCountdown = () => {
        const interval = setInterval(() => {
            if (remainingTime.value > 0) {
                remainingTime.value -= 1;
            } else {
                clearInterval(interval);   
            }
        }, 1000);

        return () => clearInterval(interval);
    }

    const resetCountdown = () => {
        remainingTime.value = duration;
    }

    return {
        remainingTime,      //时间
        isActive,           //倒计时是否仍在进行
        startCountdown,     //开始倒计时
        resetCountdown      //重置倒计时
    };
}

//导出函数
export default useCountdown
